<?php

namespace  addons\qingdong\controller;


use  addons\qingdong\model\Approval as ApprovalModel;
use  addons\qingdong\model\ExamineRecord;
use addons\qingdong\model\File;
use  addons\qingdong\model\FormApproval;
use  addons\qingdong\model\Message;
use  addons\qingdong\model\Staff;
use  addons\qingdong\model\Form;
use think\Db;
use think\Exception;

/**
 * 工作审批
 */
class Approval extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


    /**
     * 审核审核记录
     */
	public function examineApprovalList(){
        $check_status=input('check_status');//1审核中、2审核通过、3审核未通过
        $formapproval_id=input('formapproval_id');//
        $times=input('times');//
        $where=[];
        if($formapproval_id){
            $where['formapproval_id']=$formapproval_id;
        }
        if($times){
            $times = explode(',', $times);
            $where['createtime']=['between',[strtotime($times[0]),strtotime($times[1])+86400-1]];
        }
        if ($check_status) {
            //0待审核、1审核中、2审核通过、3审核未通过、4撤销
            if ($check_status == 1) {
                $where['check_status'] = ['in', [0, 1]];
            } elseif ($check_status == 2) {
                $where['check_status'] = 2;
            } elseif ($check_status == 3) {
                $where['check_status'] = 3;
            } elseif ($check_status == 4) {
                $where['check_status'] = 4;
            } elseif ($check_status == 9) {
                $where['check_status'] = 9;
            }
        }
        $type       = input('type', 0);// 0 全部 1 我创建 2 下属创建
        if ($type == 1) {//我的客户
            $where['create_staff_id'] = $this->auth->id;
        } elseif ($type == 2) {//下属负责的客户
            $where['create_staff_id'] = ['in', Staff::getLowerStaffId()];
        }else{
            $where['create_staff_id'] = ['in', Staff::getMyStaffIds()];
        }

        $staff_id=$this->auth->id;
        $approvals= ApprovalModel::where($where)->where(function ($query) use ($staff_id){
            $query->where('create_staff_id',$staff_id)
                ->whereOr('','exp', Db::raw('FIND_IN_SET(' . $staff_id. ',flow_staff_ids)'));
        })->with(['createStaff','formapproval'])->order('id desc')->paginate();

       $this->success('请求成功',$approvals);
    }

    /**
     * 获取工作列表
     */
	public function getList() {
		$list = FormApproval::where([])->field('id,name,img')->select();

		$this->success('请求成功', $list);
	}


    /**
     * 获取form表单
     */
	public function getFormapproval() {
		$id = input('id');
		$form = FormApproval::where(['id' => $id])->find();
        $staff = Staff::where(['id' => ['in',explode(',', $form['flow_staff_ids'])]])->field('id,name,img')->select();
        $forminfo = Form::where(array('id'=>$form['form_id']))->find();
        $data=json_decode($forminfo['data'], true)['data']??[];
		$this->success('请求成功',['data'=>$data,'staff'=>$staff] );
	}


    /**
     * 添加审批
     */
	public function addApproval() {
		$params          = $this->request->post();
        if(empty( $params['data'])){
            $this->error('数据不能为空');
        }
        if(empty( $params['formapproval_id'])){
            $this->error('表单id不能为空');
        }

		$result = ApprovalModel::createApproval($params);

		$this->success('保存成功');
	}

    /**
     * 获取审批详情
     */
	public function getDetail(){
        $id       = input('id');
        if(empty($id)){
            $this->error('参数不能为空');
        }
        $approval=ApprovalModel::where(['id'=>$id])->with(['formapproval'])->find()->toArray();
        $type = Form::where(array('id'=>$approval['formapproval']['form_id']))->value('type');

        $form = Form::getDataValue($type,$approval['content']);
        foreach($form as $k=>$v){
            if($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile'){
                if(key_exists($v['id'],$approval['content'])){
                    if(isset($approval['content'][$v['id']]) && $approval['content'][$v['id']]){
                        $whereT['id'] = array('in',$approval['content'][$v['id']]);
                        $fileinfo = File::where($whereT)->field('id,name,file_path')->select();
                        if($fileinfo){
                            $approval['content'][$v['id']] = $fileinfo;
                        }
                    }
                }
            }elseif($v['component'] == 'select'){
                if(isset($v['config']['multiple']) &&  $v['config']['multiple'] == true){
                    if(key_exists($v['id'],$approval['content'])){
                        if(is_array($approval['content'][$v['id']]) && $approval['content'][$v['id']]){
                            $approval['content'][$v['id']] = implode(',',$approval['content'][$v['id']]);
                        }
                    }
                }
            }
        }
        if ($approval['check_status'] == 0 || $approval['check_status'] == 1) {
            $approval['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::APPROVAL_TYPE, $id);
        } else {
            $approval['is_examine'] = 0;
        }
        $approval['is_operation']=0;
        if($approval['create_staff_id'] == $this->auth->id){
            //是否可以操作
            $approval['is_operation']=1;
        }
        Message::setRead(Message::APPROVAL_TYPE,$id,$this->auth->id);
        $this->success('请求成功',$approval);
    }

    /**
     * 修改审批
     */
    public function editApproval(){
        $id     = input('id');
        $params = $this->request->post();
        $row    = ApprovalModel::where(['id' => $id, 'check_status' => ['in', [3, 4]]])->find();
        if (empty($row)) {
            $this->error('审批信息不存在');
        }
        if(empty( $params['data'])){
            $this->error('数据不能为空');
        }
        if(empty( $params['formapproval_id'])){
            $this->error('表单id不能为空');
        }
        if(empty( $params['relation_type'])){
            $this->error('关联类型不能为空');
        }

        Db::startTrans();
        try {
            $result = ApprovalModel::updateApproval($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改信息成功');
    }

    /**
     * 撤回审批
     */
	public function cancel(){
        $id       = input('id');
        $customer = ApprovalModel::where(['id' => $id, 'check_status' => ['in', [0, 1]]])->find();
        if (empty($customer)) {
            $this->error('信息不存在');
        }

        Db::startTrans();
        try {

            ApprovalModel::where(['id' => $id])->update(['check_status' => 4]);

            ExamineRecord::cancelExaminse(ExamineRecord::APPROVAL_TYPE,$id);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();;
            $this->error($e->getMessage());
        }


        $this->success('撤回成功');
    }


}
